package com.feifan.monthhelper.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.MenstrualSperiodBean;
import com.feifan.monthhelper.bean.db.MenstrualRecordBean;
import com.feifan.monthhelper.calendar.CalendarUtils;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.db.DBUtls;
import com.feifan.monthhelper.ui.adapter.MenstrualRecordAdapter;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.utils.NumberUtils;
import com.feifan.monthhelper.utils.SPUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.*;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 月经周期记录
 */
public class MenstrualRecordActivity extends BaseActivity {

    @BindView(R.id.rl_title)
    View rlTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.refresh_header)
    ClassicsHeader refreshHeader;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.ll_empty_view)
    LinearLayout llEmptyView;
    @BindView(R.id.empty_view)
    RelativeLayout emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private int page = 0;
    private MenstrualRecordAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {
        adapter = new MenstrualRecordAdapter();
    }

    @Override
    protected void initView() {
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(adapter);
//        adapter.replace(loveRecordBeans);
        loadData(true);

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 0;
            loadData(false);
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void loadData(boolean show) {
        Disposable disposable = Observable.create((ObservableOnSubscribe<List<MenstrualRecordBean>>) emitter -> {
            emitter.onNext(DBUtls.queryAllMenstrualRecord());
            emitter.onComplete();
        })
                .doOnSubscribe(disposable1 -> {
                    if (show)
                        showLoadingDialog("加载数据...");
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Function<List<MenstrualRecordBean>, List<MenstrualRecordBean>>() {
                    @Override
                    public List<MenstrualRecordBean> apply(List<MenstrualRecordBean> menstrualRecordBeans) throws Exception {
                        Collections.sort(menstrualRecordBeans);
                        return menstrualRecordBeans;
                    }
                })
                .map(new Function<List<MenstrualRecordBean>, List<MenstrualSperiodBean>>() {
                    @Override
                    public List<MenstrualSperiodBean> apply(List<MenstrualRecordBean> dayRecordBeans) throws Exception {
                        List<MenstrualSperiodBean> menstrualRecordBeans = new ArrayList<>();
                        if (dayRecordBeans == null) {
                            return menstrualRecordBeans;
                        }
                        for (int i = 0; i < dayRecordBeans.size(); i++) {
                            MenstrualRecordBean recordBean = dayRecordBeans.get(i);
                            LogUtils.d("fillCalendarView  " + GsonUtils.toJson(recordBean));
                            MenstrualSperiodBean menstrualRecordBean = new MenstrualSperiodBean();
                            menstrualRecordBean.setStartDate(recordBean.start_date);
                            menstrualRecordBean.setMenstrualPeriod(CalendarUtils.getDateSpan(recordBean.start_date, recordBean.end_date) + 1);
                            if (i == dayRecordBeans.size() - 1) {
                                String menstrual_span = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS);
                                int span_period = NumberUtils.StringToInt(menstrual_span.replaceAll("天", ""));
                                menstrualRecordBean.setMenstrualPeriodSpan(span_period);
                            } else {
                                menstrualRecordBean.setMenstrualPeriodSpan(CalendarUtils.getDateSpan(dayRecordBeans.get(i + 1).start_date, recordBean.start_date));
                            }
                            menstrualRecordBeans.add(menstrualRecordBean);
                        }
                        return menstrualRecordBeans;
                    }
                })
//                .map(new Function<List<MenstrualSperiodBean>, List<MenstrualSperiodBean>>() {
//                    @Override
//                    public List<MenstrualSperiodBean> apply(List<MenstrualSperiodBean> menstrualSperiodBeans) throws Exception {
//                        for(int i=0;i< menstrualSperiodBeans.size(); i++) {
//                            MenstrualSperiodBean  speriodBean = menstrualSperiodBeans.get(i);
//                            if(i > 0) {
//                                MenstrualSperiodBean  lastSperiodBean = menstrualSperiodBeans.get(i - 1);
//                                lastSperiodBean.setDelayDays(getDateSpan(lastSperiodBean.getStartDate(), speriodBean.getStartDate()));
//                            }
//                            if(i == menstrualSperiodBeans.size() - 1) {
//                                int offset = getDateSpan(speriodBean.getStartDate(), new Date());
//                                if(offset == 0) {
//                                    speriodBean.setDelayDays(-1);
//                                } else if(offset > 0) {
//                                    String menstrual_span = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS);
//                                    int span_period = NumberUtils.StringToInt(menstrual_span.replaceAll("天", ""));
//                                    speriodBean.setDelayDays(span_period);
//                                }
//                            }
//                        }
//                        return menstrualSperiodBeans;
//                    }
//                })
                .doOnError(o -> dismisDialog())
                .doOnComplete(() -> dismisDialog())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    List<MenstrualSperiodBean> recordBeans = o;
                    updateView(recordBeans);
                });
        addDisposable(disposable);
//        List<MenstrualRecordBean> recordBeans = DBUtls.loadLoveBy(page);
//        if(recordBeans.size() < Constant.PAGE_COUNT) {
//            refreshLayout.setEnableLoadMore(false);
//        } else {
//            refreshLayout.setEnableLoadMore(true);
//        }
//        if(page == 0) {
//            adapter.replace(recordBeans);
//            refreshLayout.finishRefresh();
//        } else {
//            adapter.add(recordBeans);
//            refreshLayout.finishLoadMore();
//        }
    }

    private void updateView(List<MenstrualSperiodBean> recordBeans) {
        adapter.replace(recordBeans);
        refreshLayout.finishRefresh();
    }


    @Override
    protected int setContentLayout() {
        return R.layout.activity_menstrual_records;
    }
}
